var gulp = require('gulp');
var gutil = require('gulp-util');
var connect = require('gulp-connect');

var uglify = require('gulp-uglify');
var cssmin = require('gulp-minify-css');
var htmlmin = require('gulp-htmlmin');
var htmlclean = require('gulp-htmlclean');

var distPath = './dist/';

gulp.task('watchs', function () {
  // 监听文件修改，当文件被修改则执行 script 任务
  gulp.watch('js/index.js', gulp.series('uglify'));
  gulp.watch('js/sphere.three.js', gulp.series('sphere'));
  gulp.watch('css/*.css', gulp.series('css'));
  gulp.watch('index.html', gulp.series('html'));
});

gulp.task('server', function () {
  connect.server({
    root: distPath,
    port: 8888,
    livereload: true,
  });
});

gulp.task('uglify', function () {
  console.log(111);
  gulp
    .src('js/index.js')
    .on('error', function (err) {
      gutil.log(gutil.colors.red('[Error]'), err.toString());
    })
    .pipe(uglify())
    .pipe(gulp.dest(distPath + 'js'))
    .pipe(connect.reload());
});

gulp.task('css', function () {
  gulp
    .src('css/*.css')
    .pipe(cssmin())
    .pipe(gulp.dest(distPath + 'css'))
    .pipe(connect.reload());
});

gulp.task('html', function () {
  return gulp
    .src('index.html')
    .pipe(htmlclean())
    .pipe(
      htmlmin({
        removeComments: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      })
    )
    .pipe(gulp.dest(distPath))
    .pipe(connect.reload());
});

gulp.task('images', function () {
  gulp.src('images/*').pipe(gulp.dest(distPath + 'images'));
  gulp.src('images/common/*').pipe(gulp.dest(distPath + 'images/common'));
  gulp.src('images/models/*').pipe(gulp.dest(distPath + 'images/models'));
  gulp.src('images/skybox/*').pipe(gulp.dest(distPath + 'images/skybox'));
});

gulp.task('base', function () {
  gulp.src('js/base/*').pipe(gulp.dest(distPath + 'js/base'));
});

gulp.task('sphere', function () {
  gulp
    .src('js/sphere.three.js')
    .pipe(gulp.dest(distPath + 'js'))
    .pipe(connect.reload());
});

gulp.task('default', gulp.series(gulp.parallel('uglify', 'css', 'html', 'images', 'base', 'sphere', 'server', 'watchs')));
